<template>
  <div style="margin-top: 51px">
    <sunDrawerBack show="show_expertsList" :parent="this.$parent.$parent" />
    <el-page-header class="sun-el-page-header" content="分配专家" @back="goBack" />
    <sunSearch :search="searchList" />
    <el-form ref="refForm" style="display: none;" :model="formData" :rules="formRules">
      <el-form-item
        label="名称"
        prop="teacherIds"
      >
        <el-input v-model="formData.teacherIds" />
      </el-form-item>
    </el-form>
    <el-card class="sun-el-card" style="margin-bottom: 94px !important;">
      <sunUpdataAdd :title="this.$route.meta.title" :show-adddata="false" :tab-list="tabList" />
      <el-table
        ref="table"
        v-loading="loading"
        :data="list"
        element-loading-text="数据加载中..."
        border
        fit
        highlight-current-row
        :header-cell-style="{color:'#000000'}"
        @selection-change="selectionChange"
      >
        <el-table-column v-if="select_index === 0" key="0" type="selection" align="center" width="55" prop="30" />
        <el-table-column v-if="select_index === 0" key="1" label="姓名" prop="name" />
        <el-table-column v-if="select_index === 0" key="2" align="center" label="职称" prop="job_title.name" />
        <el-table-column v-if="select_index === 0" key="3" align="center" label="电话" prop="mobile" />
        <el-table-column v-if="select_index === 0" key="4" align="center" label="学校">
          <template slot-scope="{row}">
            {{ row.school_name ? row.school_name : '本校' }}
          </template>
        </el-table-column>
        <el-table-column v-if="select_index === 1" key="5" label="分组名称" prop="name" :width="150">
          <template slot-scope="{row}">
            <div class="flex_center_align">
              {{ row.name }}
              <img v-if="row.is_check" style="width: 16px;margin-left: 10px;" src="@/assets/static/edit.png" alt="" @click="expertOperation('editName', row, null)">
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="select_index === 1" key="6" label="分组专家" prop="name">
          <template slot-scope="{row}">
            <span v-for="expert in row.experts" :key="expert.id">
              <div style="display: inline-block;width: 240px;">
                <div class="flex_center_align">
                  <strong>{{ expert.teacher.name }}：
                    <span style="color:#999999">{{ expert.teacher.mobile }}</span>
                  </strong>
                  <img v-if="row.is_check" style="width: 16px;margin-left: 10px;" src="@/assets/static/replace.png" alt="" @click="expertOperation('replaceExpert', row, expert)">
                  <img v-if="row.is_check" style="width: 16px;margin-left: 10px;" src="@/assets/static/del.png" alt="" @click="expertOperation('removeExpert', row, expert)">
                </div>
                <span><strong style="color:#999999">职称：</strong>{{ expert.teacher.job_title ? expert.teacher.job_title.name : '暂无' }}</span>
                <span style="display: inline-block;padding-top: 5px;"><strong style="color:#999999;margin-left: 20px;">学校：</strong>{{ expert.teacher.school_name ? expert.teacher.school_name : '本校' }}</span>
              </div>
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="select_index === 1" key="7" align="center" label="操作" :width="100">
          <template slot-scope="{row}">
            <el-button :type="row.is_check ? 'primary' : ''" style="width: 70px" size="mini" @click="setGroup(row)">
              {{ row.is_check ? '已选择' : '选 择' }}
            </el-button>
            <el-button type="danger" :disabled="!row.is_check" style="width: 70px;margin: 10px 0 0 0" size="mini" @click="expertOperation('delGroups', row, null)">
              解 散
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div class="sun-drawer-base-btn">
      <el-button size="mini" @click="goBack">取 消</el-button>
      <el-button v-for="btn in dialogFooterBtn" :key="btn.model" :disabled="!validate_expertsList" type="primary" size="mini" @click="dialogOperationsBnt(btn)">
        {{ btn.name }}
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { $butRequest } from '@/sun-components/SunProcessButRequests.js'
import { $tooltips } from '@/sun-components/SunMsg.js'
import { $remove /** $dialogs */ } from '@/sun-components/SunMsg.js'
import SunDrawerBack from '@/sun-components/SunDrawerBack'
import SunUpdataAdd from '@/sun-components/SunUpdataAdd'
import SunSearch from '@/sun-components/SunSearch'
import { $refactorPushFront } from '@/sun-components/SunRefactorList.js'
export default {
  name: 'ProcessCommonEvaluationExpertsList',
  components: { SunDrawerBack, SunUpdataAdd, SunSearch },
  props: {
    source: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: [],
      tabList: [],
      tabItem: {},
      formRules: {},
      is_submit: false,
      formData: { // 为验证而生
        teacherIds: ''
      },
      searchList: [],
      dialogFooterBtn: [],
      searchFilter: {},
      validate_expertsList: false,
      select_index: '',
      expertsListData: [],
      allocation_group_btn: {},
      loading: false
    }
  },
  computed: {
    show_expertsList() {
      return this.$parent.$parent.show_expertsList
    },
    isExpertGroupsUpdata() {
      return this.$parent.$parent.isExpertGroupsUpdata
    },
    ...mapGetters([
      'publicRoute'
    ])
  },
  watch: {
    select_index: {
      handler: function(index) {
        if (index === 0) {
          this.searchList = [
            { 'multi_names': '姓名', type: 'input', show: 'multi_names', value: '', span: 12, eng: true },
            { 'mobile': '电话', type: 'input', show: 'mobile', value: '' }
          ]
        }
        if (index === 1) {
          this.searchList = [
            { 'name': '名称', type: 'input', show: 'name', value: '' }
          ]
        }
      }
    },
    show_expertsList: {
      handler: function(show) {
        if (show) {
          this.select_index = 0
          this.$set(this.formRules, 'teacherIds', [{ required: true, trigger: ['blur', 'change'], info: '未选择专家', validator: this.$onValidator }])
          this.requestData()
        }
      }
    },
    formData: {
      handler: function(val) {
        this.$refs.refForm.validate(valid => {
          this.validate_expertsList = valid
        })
      },
      deep: true
    },
    isExpertGroupsUpdata: {
      handler: function(val) {
        if (val) {
          this.upData()
        }
      }
    }
  },
  created() {
    if (this.show_expertsList) {
      this.select_index = 0
      this.$set(this.formRules, 'teacherIds', [{ required: true, trigger: 'blur', info: '未选择专家', validator: this.$onValidator }])
      this.requestData()
    }
  },
  methods: {
    async setGroup(row) {
      const _that = this
      const btn = this.allocation_group_btn
      _that.is_submit = true
      const setObjItem = {
        teacher_ids: row.teacher_ids,
        ..._that.$parent.$parent.currentItem
      }
      $butRequest(btn, setObjItem)
        .then((response) => {
          $tooltips(`分配成功!`, 'success')
          _that.goBack()
          _that.$parent.$parent.upData()
          _that.is_submit = false
        })
    },
    async expertOperation(type, row, expert) {
      const _that = this
      _that.$set(_that.$parent.$parent, 'expertGroupsData', {})
      if (_that.publicRoute === 'admin') { // 设置专家分组编辑时的参数
        if (_that.$parent.$parent.currentItem.group_id) {
          _that.$set(_that.$parent.$parent.expertGroupsData, 'evaluation_course_group_id', _that.$parent.$parent.currentItem.id)
        } else {
          _that.$set(_that.$parent.$parent.expertGroupsData, 'evaluation_course_id', _that.$parent.$parent.currentItem.id)
        }
      }
      if (_that.publicRoute === 'user') { // 设置专家分组编辑时的参数
        if (_that.$parent.$parent.currentItem.group_id) {
          _that.$set(_that.$parent.$parent.expertGroupsData, 'evaluation_course_group_id', _that.$parent.$parent.currentItem.id)
        } else {
          _that.$set(_that.$parent.$parent.expertGroupsData, 'evaluation_course_id', _that.$parent.$parent.currentItem.id)
        }
      }
      _that.$set(_that.$parent.$parent, 'isExpertGroupsUpdata', false)
      _that.$set(_that.$parent.$parent.expertGroupsData, 'type', type)
      _that.$set(_that.$parent.$parent.expertGroupsData, 'path_id', row.id)
      let api = ''
      switch (type) {
        case 'delGroups': // 解散
          if (_that.source === 'old') api = 'evaluation/course/expert/groups'
          if (_that.source === 'new') api = 'new/evaluation/course/expert/groups'
          $remove(`${api}/${row.id}`, _that, '确定解散专家组?')
          break
        case 'replaceExpert': // 替换
          _that.$parent.$parent.expertsListData = _that.expertsListData
          _that.$set(_that.$parent.$parent.expertGroupsData, 'sync_type', '1')
          _that.$set(_that.$parent.$parent.expertGroupsData, 'replace_or_remove', 'replace')
          _that.$set(_that.$parent.$parent.expertGroupsData, 'old_teacher_id', expert.teacher.id)
          break
        case 'removeExpert': // 移除
          _that.$parent.$parent.expertsListData = []
          _that.$set(_that.$parent.$parent.expertGroupsData, 'name', row.name)
          _that.$set(_that.$parent.$parent.expertGroupsData, 'expertName', expert.teacher.name)
          _that.$set(_that.$parent.$parent.expertGroupsData, 'sync_type', '1')
          _that.$set(_that.$parent.$parent.expertGroupsData, 'replace_or_remove', 'remove')
          _that.$set(_that.$parent.$parent.expertGroupsData, 'old_teacher_id', expert.teacher.id)
          break
        case 'editName': // 修改名称
          _that.$parent.$parent.expertsListData = []
          _that.$set(_that.$parent.$parent.expertGroupsData, 'name', row.name)
          break
      }
      if (type === 'delGroups') return
      this.$parent.$parent.show_expertGroups = true
    },
    async dialogOperationsBnt(btn) {
      this.$parent.$parent.initReserveSelection()
      this.$parent.$parent.dialogOperationsBnt(btn)
    },
    async tabHeaderSelect(id) {
      const _that = this
      _that.tabList?.forEach((item, index) => {
        if (item.old_id === id) {
          return false
        }
        if (item.id === id) {
          item.type = 'primary'
          _that.select_index = index
          _that.searchFilter = {}
          _that.tabItem = item
          _that.upData()
        } else {
          item.type = 'mini'
        }
        item.old_id = id
      })
    },
    async requestData() {
      const _that = this
      const btn = this.$parent.$parent.set_advance_request
      if (btn.model === 'allocation_expert' || btn.model === 'batch_allocation_expert') { // 确保接口的准确性
        btn.children.forEach((item, index) => {
          _that.$set(item, 'id', index + 1)
          _that.$set(item, 'old_id', 1)
          _that.$set(item, 'type', index === 0 ? 'primary' : 'mini')
        })
        _that.tabItem = btn.children[_that.select_index]
        _that.tabList = btn.children
        _that.upData()
      } else {
        $tooltips('请求终止,流程错误!')
      }
    },
    async searchResult(filter) {
      this.searchFilter = filter
      this.upData()
    },
    async upData() {
      const _that = this
      const btn = _that.tabList[_that.select_index]
      const objItem = _that.$parent.$parent.currentItem
      const experts_ids = []
      if (btn.children) {
        _that.allocation_group_btn = btn.children[0]
      }
      _that.dialogFooterBtn = btn.children ? btn.children : []
      objItem.experts?.forEach(item_id => {
        experts_ids.push(item_id.teacher_id)
      })
      if (_that.select_index === 1 && btn.model === 'tab') {
        Object.assign(_that.searchFilter, { 'teacher_ids': experts_ids.join(',') })
      }
      _that.loading = true
      $butRequest(btn, objItem, _that.searchFilter)
        .then((response) => {
          const list = $refactorPushFront(response, experts_ids)
          _that.list = list
          if (_that.select_index === 0) {
            _that.expertsListData = list
          }
          // if (_that.select_index === 0) {
          //   _that.expertsListData = response
          // }
          _that.loading = false
          setTimeout(() => {
            _that.list.forEach((item) => {
              if (experts_ids.includes(item.id)) {
                _that.$refs.table.toggleRowSelection(item, true)
              }
            })
          }, 200)
        })
    },
    async selectionChange(list) {
      const _that = this
      _that.$parent.$parent.teacherIds = []
      _that.formData.teacherIds = list.length === 0 ? '' : '选择专家'
      list.forEach((item) => {
        _that.$parent.$parent.teacherIds.push(item.id)
      })
    },
    async goBack() {
      this.$parent.$parent.initReserveSelection()
      this.$parent.$parent.setShowHidden(['show_expertsList'])
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '@/styles/sun-style.scss';
</style>
